package com.example.ykbboom.broadcastpractice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

/**
 * @author ykbboom
 * @email ykbpro@whut.edu.cn
 * @time 2017-1-22 17:17:03
 * 功能:基础类
*/
public class BaseActivity extends AppCompatActivity {

    private ForceOffLineReceiver forceOffLineReceiver;
//    private LocalBroadcastManager localBroadcastManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        ActivityManager.addActivity(this);
    }

    /**
     *初始化广播接收器 注册
    * */
    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.ykbboom.FORCE_OFFLINE");
        forceOffLineReceiver = new ForceOffLineReceiver();
//        localBroadcastManager = LocalBroadcastManager.getInstance(this);
       /*localBroadcastManager.*/registerReceiver(forceOffLineReceiver,intentFilter);//广播接收器注册
    }

    /**
     * 注销广播接收器
     * 存在问题：如果原因导致onPause执行，则会注销接收器。
     * */
    @Override
    protected void onPause() {
        super.onPause();
        if (forceOffLineReceiver!=null){
            /*localBroadcastManager.*/unregisterReceiver(forceOffLineReceiver);
            forceOffLineReceiver = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityManager.removeActivity(this);
    }

    class ForceOffLineReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(final Context context, Intent intent) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("警告");
            builder.setMessage("强制下线，请再次登录。");
            builder.setCancelable(false);
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityManager.finishAll();//销毁所有活动
                            Intent intent1 = new Intent(context,LoginActivity.class);
                            context.startActivity(intent1);
                        }
                    });

            Log.d("test","---------------------------OKOKOKOKOKOKOK------------------------");
            builder.show();
//            Toast.makeText(context,"55555",Toast.LENGTH_SHORT).show();
        }
    }
}
